﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Pub.Lib;
using Pub.Tools;

namespace Pub.Controls.MastForm
{
    public partial class BaseSelect : Pub.Controls.MastForm.BaseDlg
    {
        public BaseSelect()
        {
            InitializeComponent();
        }

        private string strFind = string.Empty;
        private string strXmlResult = string.Empty;
        private string strFieldType = "C";
        private DataTable dtSource;
        private DataTable dtlist;

        private DateTimePicker dtp = new DateTimePicker();//这里实例化一个DateTimePicker控件  


        private string _SQL = string.Empty;

        /// <summary>
        /// 执行的SQL语句
        /// </summary>
        [Category("Define"), Description("执行的SQL语句")]
        public string SQL
        {
            set
            {
                this._SQL = value;
            }
            get
            {
                return this._SQL;
            }
        }

        private string _FieldWidth = string.Empty;
        [Category("Define"), Description("字段宽度")]
        public string FieldWidth
        {
            set
            {
                this._FieldWidth = value;
            }
            get
            {
                return this._FieldWidth;
            }
        }

        private string _SortOrder = string.Empty;


        [Category("Define"), Description("排序字段")]
        public string SortOrder
        {
            set
            {
                this._SortOrder = value;
            }
            get
            {
                return this._SortOrder;
            }
        }

        [Category("Define"), Description("窗体文本")]
        public string FormText
        {
            set
            {

                this.Text = value;
            }
            get
            {
                return this.Text;
            }
        }

        private Boolean _AllowMulti = true;
        [Category("Define"), Description("允许多选")]
        public Boolean AllowMulti
        {
            set
            {
                this._AllowMulti = value;
            }
            get
            {
                return this._AllowMulti;
            }
        }

        private string _FieldCaption = string.Empty;

        [Category("Define"), Description("字段显示文本")]
        public string FieldCaption
        {
            set
            {
                this._FieldCaption = value;
            }
            get
            {
                return this._FieldCaption;
            }
        }


        private string _ResultCode = string.Empty;

        [Category("Define"), Description("返回结果:编码")]
        public string ResultCode
        {
            get
            {
                return this._ResultCode;
            }
        }

        private string _ResultName = string.Empty;

        [Category("Define"), Description("返回结果:名称")]
        public string ResultName
        {
            get
            {
                return this._ResultName;
            }
        }

        private void BaseSelect_Resize(object sender, EventArgs e)
        {
            if (this.Width < 480)
            {
                this.Width = 480;
            }
        }

        private void SetAllList(Boolean bl)
        {
            //dtlist为空,返回
            if (dtlist == null) { return; }


            //dtlist不包含_bCheck字段,返回
            if (!dtlist.Columns.Contains("_bCheck"))
            {
                return; 
            }

            for (int i = 0; i < dtlist.Rows.Count; i++)
            {
                dtlist.Rows[i]["_bCheck"] = bl;
            }
        }



        private void BaseSelect_Load(object sender, EventArgs e)
        {
            this.gridEx1.ReadOnly = false;

            btnShowALL.LinkBehavior = LinkBehavior.NeverUnderline;
            btnShowALL.LinkColor = SystemColors.HotTrack; 

            BaseSelect_Resize(null, null);
            this.AcceptButton = null;

            //  dtp.Width = 110;
            dtp.Value = DateTime.Now;
            dtp.Format = DateTimePickerFormat.Custom;
            dtp.CustomFormat = "yyyy-MM-dd";
            dtp.Width = txtSch.Width;
            cbbBL.Width = txtSch.Width;
            ToolStripControlHost host1 = new ToolStripControlHost(dtp);

            toolStrip2.Items.Insert(6, host1);

            btnChooice.Visible = _AllowMulti;

            dtSource = Helper.DBHelper.GetDataTable(_SQL, PubVar.ConnMain);
            if (dtSource == null) { return; }

            string[] strArrCaption = System.Text.RegularExpressions.Regex.Split(_FieldCaption, @"[,]+");

            ddlSearch.Items.Clear();
            for (int i = 0; i < dtSource.Columns.Count; i++)
            {
                string FDCaptin = string.Empty;
                try
                {
                    FDCaptin = strArrCaption[i];
                }
                catch
                {
                    FDCaptin = dtSource.Columns[i].ToString();
                }
                dtSource.Columns[i].Caption = FDCaptin;
                if (dtSource.Columns[i].DataType == System.Type.GetType("System.String"))
                {
                    ddlSearch.Items.Add(new ListItem("C" + dtSource.Columns[i].ToString(), FDCaptin));
                }
                else
                {
                    if ((dtSource.Columns[i].DataType.ToString().ToLower().IndexOf("int") > 0) || (dtSource.Columns[i].DataType == System.Type.GetType("System.Decimal")) || (dtSource.Columns[i].DataType == System.Type.GetType("System.Double"))) //数字
                    {
                        ddlSearch.Items.Add(new ListItem("I" + dtSource.Columns[i].ToString(), FDCaptin));
                    }
                    else
                    {
                        if (dtSource.Columns[i].DataType == System.Type.GetType("System.DateTime")) //日期
                        {
                            ddlSearch.Items.Add(new ListItem("D" + dtSource.Columns[i].ToString(), FDCaptin));
                        }
                        else
                            if (dtSource.Columns[i].DataType == System.Type.GetType("System.Boolean")) //布尔
                            {
                                ddlSearch.Items.Add(new ListItem("B" + dtSource.Columns[i].ToString(), FDCaptin));
                            }

                    }
                }
            }


            if (ddlSearch.Items.Count > 0)
            {
                ddlSearch.SelectedIndex = 1;
            }
            else
            {
                ddlSearch.SelectedIndex = 0;
            }

            this.Show();  //配合获取焦点
            this.txtSch.Focus(); //获取焦点

            //  FindData();

        }

        private void TSMAll_Click(object sender, EventArgs e)
        {
            SetAllList(true);
        }

        private void TSMAllCancel_Click(object sender, EventArgs e)
        {
            SetAllList(false);
        }

        private void TSMNot_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dtlist.Rows.Count; i++)
            {
                Boolean bl = SysTools.ToBoolean(dtlist.Rows[i]["_bCheck"].ToString());
                dtlist.Rows[i]["_bCheck"] = !bl;
            }
        }

        private string ReadddlNumberOprValue()
        {
            string strResult = string.Empty;
            string[] strArray = System.Text.RegularExpressions.Regex.Split(">=, >, <=, <,=, <>", @"[,]+");
            strResult = strArray[ddlNumberOpr.SelectedIndex];
            return strResult;
        }

        private void setddlNumberOpr()
        {
            ddlNumberOpr.Items.Clear();
            dtp.Visible = false;
            txtSch.Visible = false;
            cbbBL.Visible = false;
            switch (strFieldType.ToUpper())
            {
                case "C":
                    {
                        ddlNumberOpr.Items.Add("包含");
                        txtSch.Visible = true;
                        break;
                    }
                case "I":
                    {
                        //"=",">=",">","<=","<","<>"
                        this.ddlNumberOpr.Items.AddRange(new object[] { "大于等于", "大于", "小于等于", "小于", "等于", "不等于" });
                        txtSch.Visible = true;
                        break;
                    }
                case "D":
                    {
                        //"=",">=",">","<=","<","<>"
                        this.ddlNumberOpr.Items.AddRange(new object[] { "大于等于", "大于", "小于等于", "小于", "等于", "不等于" });
                        dtp.Visible = true;
                        break;
                    }
                case "B":
                    {
                        //"=",">=",">","<=","<","<>"
                        cbbBL.SelectedIndex = 0;
                        ddlNumberOpr.Items.Add("等于");
                        cbbBL.Visible = true;
                        // 
                        break;
                    }
            }
        }

        private void FindData()
        {
            this.Cursor = Cursors.WaitCursor;
            string strtxtSch = txtSch.Text;
            string[] strArray = System.Text.RegularExpressions.Regex.Split(strtxtSch, @"[ ]+");

            ListItem listitem = ddlSearch.SelectedItem as ListItem;
            string strFieldName = listitem.ID.ToString();
            strFieldName = strFieldName.Substring(1, strFieldName.Length - 1);
            strFind = string.Empty;

            switch (strFieldType.ToUpper())
            {
                case "C":
                    {
                        if (txtSch.Text != string.Empty)
                        {
                            string strFH = " And ";
                            if (rbOr.Checked)
                            {
                                strFH = " Or ";
                            }
                            foreach (string i in strArray)
                            {
                                if (strFind == string.Empty)
                                {
                                    strFind += "(" + strFieldName + " like '%" + i.ToString() + "%')";
                                }
                                else
                                {
                                    strFind += strFH + " (" + strFieldName + " like '%" + i.ToString() + "%')";
                                }
                            }
                        }
                        break;
                    }
                case "I":
                    {
                        if (txtSch.Text != string.Empty)
                        {
                            strFind = strFieldName + ReadddlNumberOprValue() + txtSch.Text;
                        }
                        break;
                    }
                case "D":
                    {
                        strFind = strFieldName + ReadddlNumberOprValue() + "'" + dtp.Value.ToString("d") + "'";
                        break;
                    }

                case "B":
                    {
                        if (strFieldType.ToUpper() == "B")
                        {
                            if (cbbBL.SelectedIndex == 0)
                            {
                                strFind = strFieldName + " = True";
                            }
                            else
                            {
                                strFind = strFieldName + " = False";
                            }
                        }
                        break;
                    }
            }


            DataRow[] drUserUrl = dtSource.Select(strFind, _SortOrder);

            dtlist = null;
            if (drUserUrl.Length > 0)
            {
                DataSet dsUserUrl = new DataSet();
                dsUserUrl.Merge(drUserUrl);
                dtlist = dsUserUrl.Tables[0];
            }
            else
            {
                dtlist = dtSource.Clone();   //复制表结构             
            }
            btnOK.Enabled = dtlist.Rows.Count > 0 ? true : false;

            lblCount.Text = dtlist.Rows.Count.ToString();


            if (_AllowMulti)
            {
                DataColumn dc = new DataColumn();
                dc.DataType = System.Type.GetType("System.Boolean");
                dc.DefaultValue = "False";
                dc.ColumnName = "_bCheck";
                dtlist.Columns.Add(dc);
            }
            dtlist.AcceptChanges();

            this.bindingSource1.DataSource = dtlist;
            this.gridEx1.DataSource = this.bindingSource1;

            this.gridEx1.AutoGenerateColumns = true; //自动产生列
            string[] strArrFieldWidth = System.Text.RegularExpressions.Regex.Split(_FieldWidth, @"[,]+"); //设置列宽

            int FrmWidth = 0;
            for (int i = 0; i < dtlist.Columns.Count; i++)
            {
                int intWidth = 60;

                intWidth = Pub.Tools.SysTools.ToInt(strArrFieldWidth[i]);

                this.gridEx1.Columns[i].DisplayIndex = i ;
                this.gridEx1.Columns[i].Visible = true;
                this.gridEx1.Columns[i].Width = intWidth;
             //   this.gridEx1.Columns[i].ReadOnly = true;
                this.gridEx1.Columns[i].HeaderText = dtlist.Columns[i].Caption.ToString();

                FrmWidth = FrmWidth + intWidth;
            }
            if (this.Width < FrmWidth) { this.Width = FrmWidth; }
            int iMax = dtlist.Columns.Count - 1;
            if (_AllowMulti)
            {
                //dtlist.Columns[iMax].ReadOnly = false;
                this.gridEx1.Columns[iMax].ReadOnly = false;
                this.gridEx1.Columns[iMax].HeaderText = "-";
                this.gridEx1.Columns[iMax].Width = 30;
                this.gridEx1.Columns[iMax].DisplayIndex = 0;
                
                    

              //  ((AutoFilterColumnHeaderCell)this.gridEx1.Columns[iMax].HeaderCell).FilteringEnabled = false;

            }

            this.Cursor = Cursors.Default;

        }

        private void btnOK_Click(object sender, EventArgs e)
        {

            string txtCode = string.Empty;
            string txttmp = string.Empty;
            string txttmp2 = string.Empty;
            string txtName = string.Empty;

            int x = this.gridEx1.CurrentRow.Index;    //取得选中行的索引   
            if (!_AllowMulti)
            {
                txtCode = dtlist.Rows[x][0].ToString();
                txtName = dtlist.Rows[x][1].ToString();
            }
            else
            {

                if (dtlist.GetChanges() == null)
                {
                    Pub.Tools.MsgTools.InfoMsg("请先选择后再按确定.");
                    return;
                }

                string filter = AutoFilterColumnHeaderCell.GetFilterStatus(this.gridEx1);
                DataRow[] drUserUrl = dtlist.GetChanges().Select(filter);


                //sdaAdapter.FillSchema(dsSet, SchemaType.Source);

                DataTable tmpdt = null;
                if (drUserUrl.Length > 0)
                {
                    DataSet dsUserUrl = new DataSet();
                    dsUserUrl.Merge(drUserUrl);
                    tmpdt = dsUserUrl.Tables[0];
                }
                else
                {
                    tmpdt = dtlist.Clone();   //复制表结构             
                }

                if (tmpdt != null)
                {
                    for (int i = 0; i < tmpdt.Rows.Count; i++)
                    {
                        Boolean bl = SysTools.ToBoolean(tmpdt.Rows[i][dtlist.Columns.Count - 1].ToString());
                        if (bl)
                        {
                            txtCode += (String.IsNullOrEmpty(txtCode) ? "" : ",") + "'" + tmpdt.Rows[i][0].ToString() + "'";
                            txtName += (String.IsNullOrEmpty(txtName) ? "" : ",") + "'" + tmpdt.Rows[i][1].ToString() + "'";
                        }
                    }
                }
            }

            _ResultCode = txtCode;
            _ResultName = txtName;

            this.DialogResult = DialogResult.OK;

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void ddlSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtSch.Text = string.Empty;

            ListItem listitem = ddlSearch.SelectedItem as ListItem;
            strFieldType = listitem.ID.ToString();
            strFieldType = strFieldType.Substring(0, 1);
            setddlNumberOpr();
            panelChar.Visible = strFieldType == "C";


            if ((ddlNumberOpr.Visible) && (ddlNumberOpr.SelectedIndex == -1))
            {
                txtSch.Focus();
                ddlNumberOpr.SelectedIndex = 0;
                return;
            }
            FindData();
        }

        private void ddlNumberOpr_SelectedIndexChanged(object sender, EventArgs e)
        {
            FindData();
            txtSch.Focus();
        }

        private void txtSch_TextChanged(object sender, EventArgs e)
        {
            if (strFieldType == "C")
            {
                FindData();
            }
        }

        private void rbAnd_CheckedChanged(object sender, EventArgs e)
        {
            if (((RadioButton)sender).Checked)
            {
                FindData();
            }
        }

        private void btnShowALL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Pub.Controls.AutoFilterColumnHeaderCell.RemoveFilter(this.gridEx1);
        }

        private void gridEx1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            String filterStatus = Pub.Controls.AutoFilterColumnHeaderCell.GetFilterStatusText(this.gridEx1);
            if (String.IsNullOrEmpty(filterStatus))
            {

                btnShowALL.Visible = false;
                tslMess.Visible = false;
            }
            else
            {
                btnShowALL.Visible = true;
                tslMess.Visible = true;
                tslMess.Text = filterStatus;
            }
        }

        private void btnChooice_Click(object sender, EventArgs e)
        {
            MenuStripShowRight(sender, contextMenuStrip1, e);
        }

        private void MenuStripShowRight(object sender, ContextMenuStrip MenuStrip, EventArgs e)
        {
            int _x = panelright.Location.X + ((Button)sender).Location.X + 1;
            int _y = ((Button)sender).Location.Y + ((Button)sender).Parent.Parent.Location.Y + ((Button)sender).Height - 5;
            Point point = new Point(_x, _y);
            MenuStrip.Show(this, point);
        }


    }
}
